I'm fetching data from an API as an options in Material UI Autocomplete, the options fetched correctly but the problem is when I choose an option and send it back to the API (POST) the option (category) doesn't show as a text it shows as a number (0) as shown in the image below (Mongodb)

import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';
export default function Write() {
const [categories, setCategories] = useState("");
const handlerSubmit = async (e) => {
e.preventDefault();
const newPost = {
username: user.username,
title,
categories,
} if (file) {
try {
} catch (err) {
}
}
try {
const res = await axios.post("/posts", newPost);
} catch (err) {
}
}
useEffect(() => {
const getCats = async () => {
const res = await axios.get("/categories");
setCategories(res.data);
};
getCats();
}, []);
return (
<div className='write'>
<form className="writeForm" onSubmit={handlerSubmit}>
<input
className="writeTitleInput"
required
type="text"
placeholder="title"
autoFocus={true}
onChange={e => setTitle(e.target.value)}>
</input>
<Autocomplete
multiple
limitTags={3}
id="tags-standard"
options={categories}
getOptionLabel={option => (option.name ? option.name : "")}
onChange={(e) => setCategories(e.target.value)}
renderInput={(params) => (
<TextField
{...params}
variant="standard"
label="Multiple values"
placeholder="Choose a Category"
/>
)}
/>
<button className="writeSubmitButton" type="submit">Publish</button>
</form>
</div>
)
}
The question is how to show the chosen option as a string not array?
Per the docs, the signature of onChange for Autocomplete is
function(
event: React.SyntheticEvent,
value: T | Array<T>,
reason: string,
details?: string) => void
You are expecting the value to be in event, when in fact, it's in value. Modify your onChange callback to something like the following:
onChange={(_, value) => setCategories(value)}
value may not be in the shape your API expects, so you should try using console.log in the callback to determine its shape and then modify the above appropriately.
value is Array<T> when multiple is set, so you should probably also have your default for categories set to the same type, i.e. an empty array ([]) instead of an empty string ("").